package demo.db.dynamic.config;

import java.beans.PropertyVetoException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DataSourceUtils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import demo.javax.sql.ComboPooledDataSourceDemo;
import demo.javax.sql.DataSourceDemo;
import demo.spring.framework.jdbc.datasource.lookup.RoutingDataSourceDemo;

@Configuration
@PropertySource(value = "classpath:/db/jdbc.properties")
public class DsConfig {

    @Autowired
    private Environment environment;

    @Value("${jdbc.url}")
    private String jdbcUrl;

    /**
     * <li>@Bean注解在返回实例的方法上，如果未通过@Bean指定bean的名称，则默认与标注的方法名相同；
     * <li>@Bean注解默认作用域为单例singleton作用域，可通过@Scope(“prototype”)设置为原型作用域；
     * <li>既然@Bean的作用是注册bean对象，那么完全可以使用@Component、@Controller、@Service、@Ripository等注解注册bean，当然需要配置@ComponentScan注解进行自动扫描。
     */
    @Bean(name = "masterDS", destroyMethod = "close")
    public ComboPooledDataSource masterDS() throws PropertyVetoException {
        System.err.println("init master ds");
        return ComboPooledDataSourceDemo.init(DataSourceDemo.localUrl, DataSourceDemo.localUser,
                DataSourceDemo.localPass);
    }

    @Bean(name = "slaveDS", destroyMethod = "close")
    public ComboPooledDataSource slaveDS() throws PropertyVetoException {
        System.err.println("init slave ds");
        return ComboPooledDataSourceDemo.init(DataSourceDemo.localUrl, DataSourceDemo.localUser,
                DataSourceDemo.localPass);
    }

    @Bean(name = "routingDS")
    public RoutingDataSourceDemo routingDS(@Autowired @Qualifier("masterDS") ComboPooledDataSource masterDS,
            @Autowired @Qualifier("slaveDS") ComboPooledDataSource slaveDS) throws PropertyVetoException {
        System.err.println("init routing ds");
        RoutingDataSourceDemo ds = new RoutingDataSourceDemo();
        Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
        targetDataSources.put(RoutingDataSourceDemo.MASTER, masterDS);
        targetDataSources.put(RoutingDataSourceDemo.SLAVE, slaveDS);
        ds.setTargetDataSources(targetDataSources);
        ds.setDefaultTargetDataSource(masterDS);
        return ds;
    }

    public Environment getEnvironment() {
        return environment;
    }

    public String getJdbcUrl() {
        return jdbcUrl;
    }

}
